package testebancodedados;

import java.sql.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Banco {
    private Connection con;
    
    public Banco(){
        String url = "jdbc:postgresql://localhost/postgres";
        String user = "Fabio";
        String password = "317357";

        try {
            con = DriverManager.getConnection(url, user, password);
           

        } catch (SQLException ex) {
            Logger.getLogger(Filme.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void insert(Entity e) {
        
        String stm = "INSERT INTO "+e.tableName()+"("+e.attributes()+") VALUES("+e.numAtt()+")";
        
        try {
            PreparedStatement st = con.prepareStatement(stm);
            e.setInsert(st);
            st.executeUpdate();
            
        } catch (SQLException ex) {
            Logger.getLogger(Filme.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void select(Entity e) {
        
        String stm = "SELECT "+e.getCollums()+" FROM "+e.tableName()+" WHERE "+e.getKey();
        
        try {
            PreparedStatement st = con.prepareStatement(stm);
            e.setKey(st);
            ResultSet rs = st.executeQuery();
            e.setAtt(rs);
            
        } catch (SQLException ex) {
            Logger.getLogger(Filme.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public ResultSet select(String stm) {
        
        ResultSet res = null;
        stm = "SELECT "+stm;
        
        try {
            PreparedStatement st = con.prepareStatement(stm);
            ResultSet rs = st.executeQuery();
            res = rs;
            return res;
            
        } catch (SQLException ex) {
            Logger.getLogger(Filme.class.getName()).log(Level.SEVERE, null, ex);
        }
        return res;
    }

    void update(Entity e) {
        
        String stm = "UPDATE "+e.tableName()+" SET "+e.attLessCod()+"  WHERE "+e.getKey();
        
        try {
            PreparedStatement st = con.prepareStatement(stm);
            e.setUpdate(st);
            st.executeUpdate();
            
        } catch (SQLException ex) {
            Logger.getLogger(Filme.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    void delete(Entity e) {
        
        String stm = "DELETE FROM "+e.tableName()+" WHERE "+e.getKey();
        
        try {
            PreparedStatement st = con.prepareStatement(stm);
            e.setKey(st);
            st.executeUpdate();
            
        } catch (SQLException ex) {
            Logger.getLogger(Filme.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
